package com.leo.base.db.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.leo.base.common.DataSourceConstant;
import com.leo.base.db.DynamicRoutingDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangss
 */
@Configuration
@MapperScan(basePackages = DynamicDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory")
public class DynamicDataSourceConfig {

    static final String PACKAGE = "com.leo.dao";

    /**
     * 数据源1：创建名称为mysql的数据源，且作为默认数据源
     */
    @Primary
    @Bean(name = "mysql")
    @ConfigurationProperties(prefix = "spring.datasource.druid.mysql")
    public DataSource createMysqlDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 数据源2：创建名称为oracle的数据源
     */
    @Bean(name = "oracle")
    @ConfigurationProperties(prefix = "spring.datasource.druid.oracle")
    public DataSource createOracleDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    public DynamicRoutingDataSource dynamicDataSource(@Qualifier("mysql") DataSource mysql,
                                                      @Qualifier("oracle") DataSource oracle) {
        // 这里添加数据源
        Map<Object, Object> targetDataSource = new HashMap<>();
        targetDataSource.put(DataSourceConstant.DATASOURCE_MYSQL, mysql);
        targetDataSource.put(DataSourceConstant.DATASOURCE_ORACLE, oracle);

        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        dynamicRoutingDataSource.setTargetDataSources(targetDataSource);
        dynamicRoutingDataSource.setDefaultTargetDataSource(mysql);
        return dynamicRoutingDataSource;
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory createSqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }
}
